package com.zhenwgang.listen_books.servlet.album;

import com.zhenwgang.listen_books.repository.RelationRepo;
import com.zhenwgang.listen_books.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Violet
 * @date 2022/07/21 20:27
 **/
@WebServlet("/studio/album/add.do")
public class AddJsonServlet extends HttpServlet {

    private RelationRepo relationRepo = new RelationRepo();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession(false);
        if (session == null) {
            throw new RuntimeException("用户未登录");
        }

        UserVO currentUser = (UserVO) session.getAttribute("currentUser");
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        req.setCharacterEncoding("utf-8");
        int aid = Integer.parseInt(req.getParameter("aid"));
        String[] tidArray = req.getParameterValues("add-tid");
        List<Integer> tidList = Arrays.stream(tidArray).map(Integer::parseInt).collect(Collectors.toList());

        relationRepo.insertByAidAndTid(aid, tidList);


        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        resp.getWriter().println("绑定成功");
    }
}